package org.py.xss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import org.springframework.util.StreamUtils;

import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ReadListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 防止sql注入,xss攻击
 * 前端可以对输入信息做预处理，后端也可以做处理。
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private static String key = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
    /**
     * ↑ xss基础过滤字典，强度低，关键词较少
     * ↓ xss高强度过滤，不建议使用，会导致部分常用字段遭受到过滤,解析的josn里面字段名也会遭受过滤风险
     */
    // private static String key = "and|or|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|union|drop|create|alter|table|database|information_schema|sys|user|password|admin|root|-|+|'|\"|--|/*|*/|xp_|sp_|@@|@@version|@@servername|@@language|@@spid|@@identity|@@rowcount|@@error|@@trancount|@@transtate|@@tranlevel|@@lock_timeout|@@deadlock_priority|@@max_connections|@@max_precision|@@nestlevel|@@options|@@pack_received|@@pack_sent|@@packet_errors|@@procid|@@remserver|@@rowcount|@@servername|@@servicename|@@spid|@@textsize|@@version|@@vpid|@@connections|@@cpu_busy|@@idle|@@io_busy|@@packet_errors|@@pack_received|@@pack_sent|@@timeticks|@@total_errors|@@total_read|@@total_write|@@trancount|@@transtate|@@tranlevel|@@lock_timeout|@@deadlock_priority|@@max_connections|@@max_precision|@@nestlevel|@@options|@@pack_received|@@pack_sent|@@packet_errors|@@procid|@@remserver|@@rowcount|@@servername|@@servicename|@@spid|@@textsize|@@version|@@vpid";
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    private static String replacedString="INVALID";
    static {
        String keyStr[] = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }

    private String currentUrl;
    private byte[] cachedBody;
    private boolean bodyRead = false;

    public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
        currentUrl = servletRequest.getRequestURI();
    }

    /**覆盖getParameter方法，将参数名和参数值都做xss过滤。
     * 如果需要获得原始的值，则通过super.getParameterValues(name)来获取
     * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
     */
    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }
    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }
    @Override
    public Map<String, String[]> getParameterMap(){
        Map<String, String[]> values=super.getParameterMap();
        if (values == null) {
            return null;
        }
        Map<String, String[]> result=new HashMap<>();
        for(String key:values.keySet()){
            String encodedKey=cleanXSS(key);
            int count=values.get(key).length;
            String[] encodedValues = new String[count];
            for (int i = 0; i < count; i++){
                encodedValues[i]=cleanXSS(values.get(key)[i]);
            }
            result.put(encodedKey,encodedValues);
        }
        return result;
    }
    /**
     * 覆盖getHeader方法，将参数名和参数值都做xss过滤。
     * 如果需要获得原始的值，则通过super.getHeaders(name)来获取
     * getHeaderNames 也可能需要覆盖
     */
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (!bodyRead) {
            cacheRequestBody();
        }
        return new CachedServletInputStream(cachedBody);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        if (!bodyRead) {
            cacheRequestBody();
        }
        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(cachedBody), StandardCharsets.UTF_8));
    }

    private void cacheRequestBody() throws IOException {
        // 只缓存JSON请求体
        String contentType = getContentType();
        if (contentType != null && contentType.contains("application/json")) {
            cachedBody = StreamUtils.copyToByteArray(getRequest().getInputStream());
            if (cachedBody.length > 0) {
                String body = new String(cachedBody, StandardCharsets.UTF_8);
                String cleanedBody = cleanJsonBody(body);
                cachedBody = cleanedBody.getBytes(StandardCharsets.UTF_8);
            }
        }
        bodyRead = true;
    }

    private String cleanJsonBody(String jsonBody) {
        try {
            // 解析JSON并递归清理所有字符串值
            Object parsed = JSON.parse(jsonBody);
            Object cleaned = cleanJsonObject(parsed);
            return JSON.toJSONString(cleaned);
        } catch (Exception e) {
            // 如果JSON解析失败，直接清理字符串
            return cleanXSS(jsonBody);
        }
    }

    private Object cleanJsonObject(Object obj) {
        if (obj instanceof JSONObject) {
            JSONObject jsonObj = (JSONObject) obj;
            JSONObject cleaned = new JSONObject();
            for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
                String key = cleanXSS(entry.getKey());
                Object value = cleanJsonObject(entry.getValue());
                cleaned.put(key, value);
            }
            return cleaned;
        } else if (obj instanceof String) {
            return cleanXSS((String) obj);
        } else if (obj instanceof java.util.List) {
            java.util.List<?> list = (java.util.List<?>) obj;
            java.util.List<Object> cleaned = new java.util.ArrayList<>();
            for (Object item : list) {
                cleaned.add(cleanJsonObject(item));
            }
            return cleaned;
        }
        return obj;
    }

    private String cleanXSS(String valueP) {
        // You'll need to remove the spaces from the html entities below
        String value = valueP.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        value = cleanSqlKeyWords(value);
        return value;
    }

    private String cleanSqlKeyWords(String value) {
        String paramValue = value;
        for (String keyword : notAllowedKeyWords) {
            if (paramValue.length() > keyword.length() + 4
                    && (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) {
                paramValue = StringUtils.replace(paramValue, keyword, replacedString);
            }
        }
        return paramValue;
    }

    /**
     * 缓存的ServletInputStream
     */
    private static class CachedServletInputStream extends ServletInputStream {
        private final ByteArrayInputStream inputStream;

        public CachedServletInputStream(byte[] cachedBody) {
            this.inputStream = new ByteArrayInputStream(cachedBody);
        }

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }

        @Override
        public boolean isFinished() {
            return inputStream.available() == 0;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            // 不需要实现
        }
    }

}